// node后端服务器
const http = require("http");
const badyParser = require("body-parser");
const express = require("express");
const user = require("./api/user");
const app = express();
const server = http.createServer(app);
const { getToken, getRes } = require("./utils/tool");
const host = process.env.NODE_ENV === "dev" ? "localhost" : "10.10.195.233";
const port = 9999;
const baseUrl = "/api";
const webSocket = require("ws").Server;
const moment = require("moment");
const robotReply = require("./store/robotReply.json");

const verifyClient = (info) => {
  //传入的info参数会包括这个连接的很多信息，你可以在此处使用console.log(info)来查看和选择如何验证连接
  //   console.log('info', info);
  // console.log(info.origin);
  // var origin = info.origin.match(/^(:?.+\:\/\/)([^\/]+)/);
  //if (origin.length >= 3 && origin[2] == "blog.luojia.me") {
  //  return true; //如果是来自blog.luojia.me的连接，就接受
  //}
  // console.log("连接",origin[2]);
  return true; //否则拒绝
};

const ws = new webSocket({
  port: 8181, //监听接口
  verifyClient, //可选，验证连接函数
});

const getTime = () => moment().format("HH:mm:ss");

const serverType = {
  server: {
    name: "大箴 - 陈安然",
    dept: "行政部门",
    avatar:
      "https://webcall-oss.easyliao.net/material/30103/2022/6/15/acece8ed0aed45b89bd1dbedb51753a7.png",
    msg: "您好，很高兴为您服务！请问有什么可以为您效劳？",
  },
  robot: {
    name: "大箴智能客服",
    dept: "智能AI",
    avatar: "https://s2.loli.net/2022/07/26/rQ6tJblgVozqUHP.png",
    msg: "您好，欢迎进入在线客服咨询，请问有什么可以为您效劳？",
  },
  userInfo: {
    name: "客户",
    phone: "15858194070",
    avatar: "https://s2.loli.net/2022/07/27/XAWVKygCPtDlIBU.png",
  },
};

const clients = {}; // 所有客户端
const serverId = "0"; // 唯一客服id
let curUserId = ""; // 当前聊天客户id
const unReadObj = {};

// 初始化
ws.on("connection", (client, req) => {
  const clientName = req.url.split("userId=")[1];
  clients[clientName] = client;

  // 广播
  const broadcast = (data, userId) => {
    const parmas = JSON.stringify(data);
    // 客户发送消息给客服端
    if (!userId && clients[serverId]) {
      clients[serverId].send(parmas);
    }
    // 客服、客户发送消息回显
    if (clientName !== serverId && clients[clientName]) {
      clients[clientName].send(parmas);
    }
    // 客服发送消息给指定客户端
    if (userId && clients[userId]) {
      clients[userId].send(parmas);
    }
  };

  // 当客户打开窗口时，智能客服发送消息
  if (clientName !== serverId) {
    const parmas = {
      ...serverType["robot"],
      time: getTime(),
      type: 0,
    };
    broadcast(parmas);
  }

  // 服务器收到消息
  client.on("message", (e) => {
    const data = JSON.parse(e);
    
    // 该聊天消息已读
    if (data.unRead === 0) {
      unReadObj[data.userId] = 0;
      return;
    }

    let parmas = {
      ...data,
      time: getTime(),
      type: 1,
    };

    // 客户发送消息给客服
    if (data.isUser) {
      if (data.userType === "server") {
        if (!unReadObj[data.userId] && unReadObj[data.userId] !== 0) {
          unReadObj[data.userId] = 0;
        } else {
          unReadObj[data.userId]++;
        }
      }
      parmas = {
        from: data.userId,
        to: serverId,
        ...serverType["userInfo"],
        ...parmas,
        name: clientName,
        unRead: unReadObj[data.userId] || 0,
      };
      curUserId = data.userId;
    }

    // 客服发送消息给客户
    if (data.isServer) {
      unReadObj[data.to || curUserId] = 0;
      parmas = {
        from: serverId,
        to: data.to || curUserId,
        ...serverType["server"],
        ...parmas,
        type: 0,
      };
    }

    // 回显当前发送的消息
    broadcast(parmas);

    // 机器人回复
    if (data.userType === "robot") {
      const row = robotReply.find(
        (item) => item.Answer.indexOf(data.msg) !== -1
      );
      const parmas = {
        from: serverId,
        to: data.to || curUserId,
        ...serverType["robot"],
        time: getTime(),
        type: 0,
        msg: row
          ? row.Reply
          : "非常对不起哦，不知道怎么回答这个问题呢，我会努力学习的。",
      };
      broadcast(parmas);
    }

    // 发送到指定客户端
    else if (data.isServer && data.userType === "server") {
      broadcast(parmas, data.to || curUserId);
    }

    // 客服欢迎语
    if (data.initServer) {
      const parmas = {
        from: serverId,
        to: data.to || curUserId,
        ...serverType["server"],
        time: getTime(),
        type: 0,
      };
      broadcast(parmas);
    }
  });

  // 退出聊天
  client.on("close", () => {
    delete clients[clientName];
  });
});

// 访问前端部署的dist文件
app.use(express.static("public"));

app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.use((req, res, next) => {
  if (
    req.url !== baseUrl + "/user/login" &&
    req.url !== baseUrl + "/user/register"
  ) {
    const isToken = getToken.decrypt(req.headers.authentication, "token");
    isToken ? next() : getRes(res, 403, "登录已过期，请重新登录");
  } else {
    next();
  }
});

app.use(badyParser.json());

app.use(
  badyParser.urlencoded({
    extended: false,
  })
);

// 后端api路由
app.use(baseUrl + "/user", user);

// 启动监听
server.listen(port, host, () => {
  console.log(`success：http://${host}:${port}`);
});
